<?php

namespace App\Http\Util;

use InvalidArgumentException;

/**
 * 3DES加密解密工具类
 */
class TripleDES
{
    const CIPHER_METHOD = 'DES-EDE3';
    const KEY_SIZE = 24;//// DESede 密钥实际为 24 字节（对应 168 位有效位）

    /**
     * 生成KEY的核心方法
     * @return string
     * @throws Exception
     */
    static function generateKeyCore() {
        $keyLength = 24; // DESede 密钥实际为 24 字节（对应 168 位有效位）
        $key = openssl_random_pseudo_bytes($keyLength, $strong);
        if ($key === false || !$strong) throw new \Exception("生成随机字符串异常：无法生成强加密强度的密钥");
        return $key;
    }

    /***
     * 生成密钥
     * @return string
     * @throws Exception
     */
    public static function generateKey(){
        return bin2hex(self::generateKeyCore());
    }


    public static function encrypt($data,$inkey)
    {
        $key = hex2bin($inkey);
        if ($key === false || strlen($key) !== 24)
            throw new InvalidArgumentException('Invalid 3DES key provided. Key must be 48 hexadecimal characters.');

        // 使用3DES ECB模式进行加密，PKCS5Padding填充
        $paddedData = self::pkcs5_pad($data);
        $encrypted = openssl_encrypt($paddedData, self::CIPHER_METHOD, $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING);
        return bin2hex($encrypted);
    }

    public static function decrypt($data,$inkey)
    {
        $data = hex2bin($data);
        $key = hex2bin($inkey);
        if ($key === false || strlen($key) !== 24)
            throw new InvalidArgumentException('Invalid 3DES key provided. Key must be 48 hexadecimal characters.');
        if ($data === false)  throw new InvalidArgumentException('Invalid encrypted data provided.');
        // 使用3DES ECB模式进行解密
        $decrypted = openssl_decrypt($data, self::CIPHER_METHOD, $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING);
        return self::pkcs5_unpad($decrypted);
    }

    private static function pkcs5_pad($text, $blocksize = 8)
    {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    private static function pkcs5_unpad($text)
    {
        $pad = ord($text[strlen($text) - 1]);
        if ($pad > strlen($text) || strspn($text, chr($pad), strlen($text) - $pad) !== $pad)
            return false;
        return substr($text, 0, -1 * $pad);
    }
}
